<template>
  <div class="form-container">
    <h2>登录</h2>
    <form @submit.prevent="handleLogin">
      <input v-model="username" placeholder="用户名" required />
      <input v-model="password" type="password" placeholder="密码" required />
      <button type="submit">登录</button>
    </form>
    <p>没有账号？<router-link to="/register">注册</router-link></p>
  </div>
</template>

<script setup lang="ts">
import { ref } from 'vue'
import api from '@/utils/api'
import { useRouter } from 'vue-router'

const username = ref('')
const password = ref('')
const router = useRouter()

async function handleLogin() {
  console.log('登录信息：', username.value, password.value)
  // TODO: 发请求到后端验证登录
  try {
    const response = await api.post('/api/users/login', {
      username: username.value,
      password: password.value,
    })
    /*alert('登录成功！');*/
    console.log(response.data)
    //获取用户id
    const response_id = await api.get(`/api/users?username=${encodeURIComponent(username.value)}`)
    //return response.data; // 就是 userId
    /*存储用户昵称*/
    localStorage.setItem('username', username.value)
    // 确保存储的是用户ID而不是整个用户对象
    const userId = response_id.data.userId || response_id.data.id || response_id.data
    localStorage.setItem('userId', userId.toString())
    router.push('/home') // ✅ 登录成功跳转
  } catch (error: any) {
    alert('用户名或密码错误')
    /*alert('登录失败: ' + (error.response?.data?.message || '未知错误'));*/
    console.error(error)
  }
}
</script>

<style scoped>
body {
  background-color: #f5f5f5; /* 页面整体背景颜色 */
  margin: 0;
  font-family: Arial, sans-serif;
  height: 100vh;
  display: flex;
  justify-content: center;
  align-items: center;
}

.form-container {
  background-color: #ffffff; /* 表单区域背景白色 */
  max-width: 320px;
  width: 90%;
  padding: 24px;
  border: 1px solid #ddd;
  border-radius: 10px;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
}

h2 {
  text-align: center;
  margin-bottom: 20px;
  color: #333;
}

input {
  display: block;
  margin-bottom: 12px;
  width: 100%;
  padding: 10px;
  box-sizing: border-box;
  border: 1px solid #ccc;
  border-radius: 6px;
}

button {
  width: 100%;
  padding: 10px;
  background-color: #0086f6;
  color: white;
  border: none;
  border-radius: 6px;
  cursor: pointer;
  font-weight: bold;
  transition: background-color 0.3s;
}

button:hover {
  background-color: #0086f6;
}

p {
  text-align: center;
  margin-top: 12px;
}

a {
  color: #0086f6;
  text-decoration: none;
}

a:hover {
  text-decoration: underline;
}
</style>
